package com.zbkj.crmeb.order.channel;

import java.time.Instant;
import java.util.List;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.common.CommonResult;
import com.utils.HttpUtils;
import com.utils.RestTemplateUtil;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.request.XiYangYangOrderRequest;
import com.zbkj.crmeb.order.response.XiYangYangOrderResponse;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import cn.hutool.crypto.digest.DigestUtil;

@Service("xiYangYangStoreOrderService")
public class XiYangYangStoreOrderServiceImpl extends AbstractStoreOrderService {
    private static Logger logger = LoggerFactory.getLogger(XiYangYangStoreOrderServiceImpl.class);
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* buyer配置参数 *********/
    @Value("${xyy.url}")
    private String xurl;
    @Value("${xyy.appkey}")
    private String appkey;
    @Value("${xyy.secret}")
    private String secret;

    /**
     * 连接超时 毫秒
     */
    private static final Integer CONNECT_TIME_OUT = 5000;
    /**
     * 响应超时 毫秒
     */
    private static final Integer RESP_TIME_OUT = 30000;

    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;

    @Override
    public CommonResult addChannelOrder(StoreOrder storeOrder , List<StoreOrderInfoVo> orderInfoVoList) {
        orderInfoVoList.stream().forEach(order ->{
            if (9 != storeOrder.getSource()) {
                storeOrder.setPushOrderNo(order.getChildOrderNumber());
            }
            XiYangYangOrderRequest request = new XiYangYangOrderRequest();
            request.setSourceName("xunwu");
            request.setOutOrderSn(storeOrder.getPushOrderNo());
            request.setShipping("16");
            request.setFhrName("杨少峰");
            request.setFhrPhone("90541984");
            XiYangYangOrderRequest.SpecInfo goods = new XiYangYangOrderRequest.SpecInfo();
            goods.setQuantity(order.getInfo().getCartNum()+"");
            String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
            if(sourceSkuId.startsWith(ProductTypeEnum.XYY.getCode()+"-")){
                sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.XYY.getCode()+"-","");
            }
            String[] sourceSkuIdArr = sourceSkuId.split("-");
            String barCode = order.getInfo().getProductInfo().getBarCode();
            goods.setGoodsId(barCode.substring(4,barCode.length()));
            goods.setSpecId(sourceSkuIdArr[0]);
            request.setShId(sourceSkuIdArr[1]);
            Integer tempId = order.getInfo().getProductInfo().getTempId();
            XiYangYangOrderRequest.SpecInfo[] goodsArr = new XiYangYangOrderRequest.SpecInfo[]{goods};
            request.setInfoArr(goodsArr);
            //设置地址
            if(2 == storeOrder.getSource()){
                request.setConsignee(storeOrder.getRealName());
                request.setPhoneTel(storeOrder.getUserPhone());
                request.setAddress(storeOrder.getUserAddress());
                request.setAddress(storeOrder.getDetail());
            }else{
                setAddress(storeOrder,tempId,request);
            }
            addChannelOrder(storeOrder,request,order);
        });
        return CommonResult.success();
    }

    @Override
    public CommonResult cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }


    /**
     * 获取buyer商品数据和详情
     * @Description:
     * @author daigb
     * @param @param id 商品barCode
     * @param @return
     * @param @throws Exception
     * @return BuyerProductResDTO
     * @throws
     */
    public CommonResult addChannelOrder(StoreOrder storeOrder, XiYangYangOrderRequest request,StoreOrderInfoVo orderInfo) {
    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        XiYangYangOrderResponse response = null;
        logger.info("---------------请求喜羊羊创建订单, 商品id: {} ---------------");
        String timestamp = String.valueOf(Instant.now().getEpochSecond());
        String signature = getSignature(timestamp, timestamp);
        String result = null;
        String url = xurl+"t/"+timestamp+"/r/"+timestamp+"/appkey/"+appkey+"/secret/"+secret+"/s/"+signature;
        try {
            logger.info("--------------- 开始请求喜羊羊创建订单url: {},body:{} ---------------", url , JSONObject.toJSONString(request));
            result = HttpUtils.post(url,JSONObject.toJSONString(request),RESP_TIME_OUT,CONNECT_TIME_OUT);
            logger.info("--------------- 请求喜羊羊创建订单返回结果: {} ---------------", result);
            response = JSONObject.parseObject(result, XiYangYangOrderResponse.class);
            //buyer新增订单成功，创建采购单
            if(null!=response && !response.isError()){
                //新增采购单
                storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.XYY.getCode());
                //新增采购商品
                storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, "成功", null);
                if(storeOrder.getPushStatus()!=2){
                    storeOrder.setPushStatus(1);
                    storeOrder.setPushMessage("喜羊羊推送:"+response.getMsg());
                    storeOrderDao.updateById(storeOrder);
                    return CommonResult.success();
                }
            }
        } catch (Exception e) {
            logger.info("--------------- 请求喜羊羊创建订单失败结果: {} ---------------", e);
        }
        storeOrder.setPushStatus(2);
        storeOrder.setPushMessage("喜羊羊推送:"+response == null?"":response.getMsg());
        storeOrderDao.updateById(storeOrder);
        return CommonResult.failed(response.getMsg());
    }

    // 签名
    private String getSignature(String timestamp, String random) {
        String signStr = timestamp+random+appkey+secret;
        signStr = DigestUtil.sha1Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);
        signStr = DigestUtil.md5Hex(signStr);

        return signStr.toUpperCase();

    }

    private void setAddress(StoreOrder storeOrder,Integer tempId,XiYangYangOrderRequest request){
        //收货地大陆
        if(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).equals(AreaTypeEnum.CN)){
            if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.HK) ||
                    StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.EUR)){
                request.setAddress("中国香港东区柴灣豐業街4 號志同昌工業大廈 4 字樓 B 室");
                request.setConsignee("杨少峰");
                request.setPhoneTel("90541984");
            }else {
                request.setConsignee(storeOrder.getRealName());
                request.setPhoneTel(storeOrder.getUserPhone());
                request.setAddress(storeOrder.getDetail());
            }
            //收货地香港
        }else if(AreaTypeEnum.getTypeByCode(storeOrder.getAreaType()).equals(AreaTypeEnum.HK)){
            if(StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.HK) || StockAreaTempEnum.getByTempId(tempId).equals(StockAreaTempEnum.EUR)){
                request.setAddress("中国香港东区柴灣豐業街4 號志同昌工業大廈 4 字樓 B 室");
                request.setConsignee("杨少峰");
                request.setPhoneTel("90541984");
            }else{
                request.setConsignee(storeOrder.getRealName());
                request.setPhoneTel(storeOrder.getUserPhone());
                request.setAddress(storeOrder.getDetail());;
            }
        }else {
            request.setConsignee(storeOrder.getRealName());
            request.setPhoneTel(storeOrder.getUserPhone());
            request.setAddress(storeOrder.getDetail());
        }
    }

}
